<?php

namespace App\Http\Controllers\rootcontroller\taskcontroller;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use App\Models\DawnUser;
use App\Pojo\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Models\DawnZhjyUser;
use App\Models\ScheduleTask;
use App\Services\ScheduleServiceInterFace;
class TaskController extends Controller{
    protected $scheduleService;
    public function __construct(ScheduleServiceInterFace $scheduleService)
    {
        $this->scheduleService = $scheduleService;
    }

    public function getAllTaskDetails(Request $request){
        $request->validate([    
            'keyword' => 'nullable|string',
            'status' => 'nullable|integer',
            'page' => 'required|integer',
            'limit' => 'required|integer',
        ]);
        $page = $request->input('page');
        $limit = $request->input('limit');
        // 创建基础查询并按创建时间降序排序，关联DawnUser和DawnZhjyUser
        $query = ScheduleTask::with([
            'user', // 关联DawnUser
            'user.zhjyUser' // 关联DawnZhjyUser
        ])->where('is_active', '!=', 2)
          ->orderBy("created_at", "desc");
        
        // 如果存在搜索关键词，则添加搜索条件
        if ($request->has('keyword') && !empty($request->input('keyword'))) {
            $keyword = $request->input('keyword');
            $query->where('name', 'like', '%' . $keyword . '%');
        }
        
        // 如果存在状态筛选，则添加状态条件
        if ($request->has('status') && $request->input('status') !== null) {
            $status = $request->input('status');
            $query->where('status', $status);
        }
        
        // 获取分页数据
        $paginator = $query->paginate($limit, ['*'], 'page', $page);
        
        // 组装返回数据，包含完整用户和智慧教育信息
        $data = [
            'list' => collect($paginator->items())->map(function($task) {
                return [
                    'id' => $task->id,
                    'name' => $task->name,
                    'cron_expression' => $task->cron_expression,
                    'is_active' => $task->is_active,
                    'time_type' => $task->time_type,
                    'delay_time' => $task->delay_time,
                    'jitter_time' => $task->jitter_time,
                    'created_at' => $task->created_at,
                    'user' => $task->user ? $task->user->toArray() : null,
                    'zhjy_user' => $task->user && $task->user->zhjyUser ? $task->user->zhjyUser->toArray() : null,
                    // 其他字段...
                ];
            }),
            'total' => $paginator->total(),
            'page' => $paginator->currentPage(),
            'limit' => $paginator->perPage(),
            'total_pages' => $paginator->lastPage()
        ];
        
        return Response::success($data, '获取任务列表成功', 200);
    }


    public function updateTaskDetails(Request $request){
        $validator = Validator::make($request->all(), [
            'ids' => 'required|array',
            'is_active' => 'required|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors()
            ], 422);
        }

        $data = $validator->validated();
        $toggleData = json_encode($data['is_active']);
        
        $tasks = [];
        foreach ($data['ids'] as $id) {
            $task = $this->scheduleService->toggleTaskStatus($id, $toggleData);
            $tasks[] = $task;
        }
        
        $status = $data['is_active'] ? '启用': '暂停';
        return response::success($tasks,  "任务已{$status}");
    }   

    public function deleteTaskDetails(Request $request){
        $request->validate([    
            'ids' => 'required|array',
        ]);
        $ids = $request->input('ids');

        foreach ($ids as $id) {
            $this->scheduleService->deleteTask($id);
        }
        return response::success($ids,  "任务已删除");
    }
}